import { ref, computed } from "vue";
import { defineStore } from "pinia";
// import { getUser } from "@/services/user";
import { useRouter } from "vue-router";
import { getUser,listUserRole, listUserFunction } from "../services/user";

export const useUserStore = defineStore("user", () => {
    const user = ref({});
    const userId = ref();
    const toRoleVisible = ref(false);
    const toFunctionVisible = ref(false);
    const allRoles = ref([]);
    const assignRoles = ref([]);
    const allFunctions = ref([]);
    const assignFunctions = ref([]);
    async function fetchUser() {
        let res = await getUser();
        user.value = res.data;
    }
    async function fetchUserRole(id) {
        userId.value = id;
        let res = await listUserRole(id);
        let { all = [], assign = [] } = res.data;
        allRoles.value = all.map((item) => ({
            key: item.id,
            label: item.name,
        }));
        assignRoles.value = assign.map((item) => item.id);
    }
    async function fetchUserFunction(id) {
        userId.value = id;
        let res = await listUserFunction(id);
        let { all = [], assign = [] } = res.data;
        allFunctions.value = all.map((item) => ({
            key: item.id,
            label: item.name,
        }));
        assignFunctions.value = assign.map((item) => item.id);
    }

    return {
        user,
        userId,
        toRoleVisible,
        toFunctionVisible,
        allRoles,
        assignRoles,
        allFunctions,
        assignFunctions,
        fetchUser,
        fetchUserRole,
        fetchUserFunction
    };
});
